const http = require('http')
const {promisify} = require('util')
const fs = require('fs')
const readFile = promisify(fs.readFile)
const port  = 3001
const server = http.createServer()

server.on('request', function (request, response) {
  console.log('有人发请求了！')
  console.log(request.url)
  const url = request.url
  if(url == '/')
  readFile('index.html')
  .then(res => {
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.end(res)
  })
  .catch(err => {
    response.writeHead(500, {'Content-Type': 'text/html'})
    console.log(err)
    response.end()
  })
  else if( url.indexOf('.jpg') != -1 )  //网页读取图片
  { 
    response.writeHead(200, {'Content-Type': 'image/png'})
    const rs = fs.createReadStream('../'+url)
    let responseData = []
    rs.on( 'data', function( chunk ) {
      responseData.push( chunk )
    })
    rs.on('end', () => {
      const finalData = Buffer.concat( responseData )
      console.log('数据已读完')
      response.write(finalData)
      response.end()
    })
  }
  else if( url.indexOf('.ico') != -1 ) {
    readFile('../other/logo.jpg').then(data => {
      response.end(data)
    }).catch((err) => {
      console.log('出错啦')
      response.end()
    })
  }
  else {
    console.log('想要读取数据:'+url)

    readFile('.'+url).then(data => {
      console.log(data)
      response.end(data)
    }).catch(err => {
      console.error('出错啦')
      response.end()
    })
  }
  return
})
server.listen(port, function () {
  console.log(`${port} ready!`)
})